package book;

import constant.Constant;
import utils.AnalyzingBook;
import utils.ScannerSingleton;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Arrays;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-07-04
 * Time: 20:46
 */
//现在我们定义了一个图书馆类来从磁盘文件中读取图书
public class Library {
    public Book[] books;    //存储书籍的数组
    public int bookCount; //记录当前图书馆有效的书
    public Scanner scanner;
    private static Library library;
    private AnalyzingBook analyzingBook = new AnalyzingBook(); //读写文件的类
    private Library(){
        loadAllBook(); //保证每次都是最准确的图书数据
        scanner = ScannerSingleton.getScannerSingleton();

    }
    public static Library getLibrary(){
        if(library == null){
            return new Library();
        }
        return library;
    }
    private void loadAllBook(){     //从磁盘文件中读取图书的数据
        try{
            Book[] allBook = analyzingBook.loadObject(Constant.ALL_BOOK_FILE_NAME);
            books = new Book[Constant.CAPACITY];    //默认图书馆能存5本书
            if(allBook == null){
                bookCount = 0;
            }else{
                int allBooklen = allBook.length;
                if(allBooklen > books.length){  //如果磁盘中读取出来的图书数量比我们开的图书馆存储数量大，重新分配图书馆存储数量
                    books = new Book[allBooklen];
                }
                for (int i = 0; i < allBook.length; i++) {
                    books[i] = allBook[i];
                }
                bookCount =  allBooklen;
            }
        }catch(IOException e){
            throw new RuntimeException(e);
        }
    }
    private void storeBook(){   //内存中的数据写入到磁盘文件中
        try{
            analyzingBook.storeObject(books, Constant.ALL_BOOK_FILE_NAME);
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }
    //共用的方法
    public void searchBook() {

        System.out.println("查找图书");
        scanner.nextLine();
        System.out.println("请输入你要查找的图书的名称：");
        String title = scanner.nextLine();
        Book book = search(title);
        if(book == null) {
            System.out.println("没有你要找的这本书，你查找的书名为："+title);
        }else {
            System.out.println("找到了你要查找的书，书的详细信息如下：");
            System.out.println(book);
        }
    }
    private Book search(String title){
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getTitle().equals(title)){
                return book;
            }
        }
        return null;
    }
    public void displayBooks() {
        System.out.println("显示图书");
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            System.out.println(books[i]);
        }
    }
    public void exit() {
        System.out.println("退出系统");
        System.exit(0);
    }

    public void addBook(Book book) {
        System.out.println("Libary类addBook方法执行了");
        if(bookCount >= books.length){
            System.out.println("图书馆已满，无法上架图书");
            //扩容的 TODO 如果扩容了 下面就不要进行return了
            return;
        }
        books[bookCount] = book;
        if(bookCount == 0){ //注意当图书馆里没有图书的情况，设置图书ID的处理方法
            book.setBookId(1);
        }else{
            Book bookLast = books[bookCount - 1];
            book.setBookId(bookLast.getBookId() + 1); //保证不会出现图书Id为2的图书下架了，2后面的3,4ID的图书都要改变ID
        }
        bookCount++;
        storeBook();
        System.out.println("图书上架成功！！ 图书的名称是："+book.getTitle());
    }

    public Book searchById(int bookId) {
        loadAllBook(); //读取文件里面的数据，保证现在的图书信息一定是最新的
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            if(book.getBookId() == bookId){
                return book;
            }
        }
        return null;
    }

    public void updateBook(Book book) {
        int bookId = book.getBookId();
        int index = searchByIdReturnIndex(bookId);
        if(index == -1){
            System.out.println("没有你要更新的图书，此时的ID为："+bookId);
            return;
        }
        books[index] = book;
        storeBook();//把当前的更新 写会到 文件当中 保证一致性
        System.out.println("书籍已被更新，文件已经写入，更新之后书籍为：");
        System.out.println(books[index]);
    }

    private int searchByIdReturnIndex(int bookId) {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book =  books[i];
            if(book.getBookId() == bookId){
                return i;
            }
        }
        return -1;
    }

    public void removeBook(int bookId) {
        int index = searchByIdReturnIndex(bookId);
        if(index == -1) {
            System.out.println("没有你要删除的图书");
            return;
        }
        for (int i = index; i < bookCount - 1; i++) {
            books[i] = books[i + 1];
        }
        bookCount--;
        books[bookCount] = null;    //最后一个多余的对象设置为null

        storeBook();
    }

    public void borrowCount() {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            System.out.println("书籍："+book.getTitle()+" 借阅了："+book.getBorrowedCount()+"次！");
        }
    }

    public void generateBook(int k) {
         loadAllBook();
         Book[] tmp = new Book[bookCount]; //存放在临时数组里面进行排序，不会改变原来数组的数据，让文件和内存中的数据保持一致性
        for (int i = 0; i < bookCount; i++) {
            tmp[i] = books[i];
        }
        Arrays.sort(tmp); //按借阅次数最多开始排序，导入Comparable接口，重写CompareTO方法
        //3. 把前k本书拷贝到新数组   可以不定义临时数组，直接输出前K个就行
        Book[] generateBooks = new Book[k];
        for (int i = 0; i < k; i++) {
            generateBooks[i] = tmp[i];
        }
        //4.打印新数组
        System.out.println("最受欢迎书籍如下：");
        for (int i = 0; i < generateBooks.length; i++) {
            Book book = generateBooks[i];
            System.out.println("书籍ID: "+book.getBookId()+" |书名："+ book.getTitle()+" |作者："+
                    book.getAuthor()+" |借阅次数："+book.getBorrowedCount());
        }
    }

    public void checkInventoryStatus() {
        loadAllBook();
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            String status = "未借出";
            if(book.isBorrowed()){
                status = "已借出";
            }
            System.out.println("书籍："+book.getTitle()+" 借阅状态：" + status);
        }
    }

    public void checkAndRemoveOldBooks() {
        loadAllBook();

        // 获取当前时间戳
        long currentTimestamp = System.currentTimeMillis();
        // 将当前时间戳转换为 LocalDate
        LocalDate currentDate = Instant.ofEpochMilli(currentTimestamp)
                .atZone(ZoneId.systemDefault())
                .toLocalDate();
        boolean flag = false;
        for (int i = 0; i < bookCount; i++) {
            Book book = books[i];
            LocalDate specifiedDate= book.getShelDate();
            long yearsBetween =  ChronoUnit.YEARS.between(specifiedDate, currentDate);  // 计算两个日期之间的差值（以年为单位）
            if(yearsBetween >= 1){
                System.out.print("图书 " + book.getTitle() + " 已经上架超过一年，是否移除？ (y/n)：");
                scanner.nextLine();
                String response = scanner.nextLine();
                if (response.equalsIgnoreCase("y")) {
                    removeBook(book.getBookId());
                    i--; //我们删除是向前覆盖的，所以删除i位置，i的下一个位置覆盖，所以i因该不动，i--和i++保证了i不动
                }
                flag = true;
            }
        }
        if(!flag){
            System.out.println("没有上架超过一年的图书！");
        }
        storeBook();
    }

    public void borrowBook(int bookId) {
        loadAllBook();
        Book book = searchById(bookId);
        book.setBorrowed(true); //借阅状态为借出
        book.incrementBorrowCount();    //增加借阅次数
        storeBook();
    }

    public void returnBook(int bookId) {
        loadAllBook();
        Book book = searchById(bookId);
        book.setBorrowed(false);
        book.decreaseBorrowCount();
        storeBook();
    }
}
